package redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

public class RedisDemoHash {

    // hset 和 hget
    public static void test01(Jedis jedis) {
        jedis.flushAll();
        jedis.hset("key1", "f1", "f");
        Map<String, String> hash = new HashMap<>();
        hash.put("h1", "1");
        hash.put("h2", "1");
        hash.put("h3", "1");
        hash.put("h4", "1");
        System.out.println(jedis.hset("key2", hash));
        System.out.println(jedis.hkeys("key1"));
        System.out.println(jedis.hgetAll("key2"));
    }

    // hexists 和 hdel
    public static void test02(Jedis jedis) {
        boolean h1 = jedis.hexists("key1", "f1");
        boolean h0 = jedis.hexists("key1", "f0");
        System.out.println("h1: " + h1 + " h0: " + h0);

        System.out.println(jedis.hdel("key2", "h1", "h2"));
        System.out.println(jedis.hkeys("key2"));
        System.out.println(jedis.hvals("key2"));
        System.out.println(jedis.hgetAll("key2"));
    }

    // hmget 和 hmset
    public static void test03(Jedis jedis) {
        Map<String, String> hash = new HashMap<>();
        hash.put("h1", "1");
        hash.put("h2", "1");
        hash.put("h3", "1");
        hash.put("h4", "1");
        jedis.hmset("key3", hash);
        System.out.println(jedis.hmget("key3", "h1", "h2", "h10"));
    }

    // hlen 和 hsetnx
    public static void test04(Jedis jedis) {
        System.out.println(jedis.hlen("key1"));
        System.out.println(jedis.hlen("key2"));
        System.out.println(jedis.hsetnx("key3", "h1", "1"));
    }

    public static void test05(Jedis jedis) {
        jedis.hset("key4", "f1", "1");
        System.out.println(jedis.hincrBy("key4", "f1", 10));
        System.out.println(jedis.hincrByFloat("key4", "f1", -1));
    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool(Constant.IP);
        try (Jedis jedis = jedisPool.getResource()){
//            test01(jedis);
//            test02(jedis);
//            test03(jedis);
//            test04(jedis);
            test05(jedis);
        }
    }
}
